#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import xml.sax
import json
import sys

class PubmedMetaHandler(xml.sax.ContentHandler):
    def __init__(self):
        self.CurrentData = ""
        self.node_list = []
        self.child_node = {}
        self.attribute_node = {}
        self.content_list = {}
        self.body = 0

    def startElement(self, tag, attributes):
        if self.body == 0:
            if tag == "body":
                self.body = 1
            else:
                self.CurrentData = tag
                if len(self.node_list) != 0:
                    parent_node = self.node_list[-1]
                    if not self.child_node.has_key(parent_node):
                        self.child_node[parent_node] = {}
                    self.child_node[parent_node][tag] = 0
                if len(attributes) != 0:
                    if not self.attribute_node.has_key(tag):
                        self.attribute_node[tag] = {}
                        for attr in attributes.keys():
                            self.attribute_node[tag][attr] = 0
                self.node_list.append(tag)

    def endElement(self, tag):
        if tag == "body":
            self.body = 0
        else:
            if self.body == 0:
                self.CurrentData = ""
                self.node_list.pop()

    def characters(self, content):
        if self.body == 0:
            if content != "":
                self.content_list[self.CurrentData] = 1

    def endDocument(self):
        chil=json.dumps(self.child_node)
        attr=json.dumps(self.attribute_node)
        cont=json.dumps(self.content_list)

        print "{"
        print "\"child_node\":"
        print chil
        print ","

        print "\"attribute_node\":"
        print attr
        print ","

        print "\"content_list\":"
        print cont
        print "}"

if __name__ == "__main__":
    parser = xml.sax.make_parser()
    parser.setFeature(xml.sax.handler.feature_namespaces, 0)

    Handler = PubmedMetaHandler()
    parser.setContentHandler(Handler)

    parser.parse(sys.argv[1])

    # for item in child_node.keys():
    #     print item + "====",
    #     for item2 in child_node[item].keys():
    #         print item2 + ";",
    #     print
    # print
    # for item in attribute_node.keys():
    #     print item + "====",
    #     for item2 in attribute_node[item].keys():
    #         print item2 + ";",
    #     print
    # print
    # for item in content_list.keys():
    #     print item





